<?php

namespace app\manystore\controller\general;

use app\manystore\model\Manystore;
use app\common\controller\ManystoreBase;
use app\common\model\User;
use fast\Random;
use think\Session;
use think\Validate;

/**
 * 商家信息配置
 *
 * @icon fa fa-user
 */
class Profile extends ManystoreBase
{

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax()) {

            $model = model('ManystoreLog');

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $model
                ->where($where)
                ->where(array('manystore_pid'=> MANY_STORE_PID))
                ->order($sort, $order)
                ->count();

            $list = $model
                ->withField("money")
                ->where($where)
                ->where(array('manystore_pid'=> MANY_STORE_PID))
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 更新个人信息
     */
    public function update()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            $params = array_filter(array_intersect_key(
                $params,
                array_flip(array('email', 'nickname', 'password', 'avatar'))
            ));
            unset($v);
            if (!Validate::is($params['email'], "email")) {
                $this->error(__("Please input correct email"));
            }
            if (isset($params['password'])) {
                if (!Validate::is($params['password'], "/^[\S]{6,16}$/")) {
                    $this->error(__("Please input correct password"));
                }
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
            }
            $exist = Manystore::where('email', $params['email'])->where('id', '<>', $this->auth->id)->find();
            if ($exist) {
                $this->error(__("Email already exists"));
            }
            if ($params) {
                $admin = Manystore::get($this->auth->id);
                $admin->save($params);
                //因为个人资料面板读取的Session显示，修改自己资料后同时更新Session
                Session::set("manystore", $admin->toArray());

                // // 获取管理员关联用户的 基本信息
                $userid = isset($admin->toArray()['userid'])?intval($admin->toArray()['userid']):0;
                if($userid > 0){
                    Session::set("manystoreuserinfo", User::get($userid));
                }else{
                    Session::set("manystoreuserinfo", []);
                }

                $this->success();
            }
            $this->error();
        }
        return;
    }
}
